package com.zl.tby.core.context.tools;

import org.noear.solon.annotation.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author changpeng
 * @version 1.0
 * @since 2025/6/6 12:20
 */
@Component
public class HttpURLConnectionUtil {

    /**
     * 发送 GET 请求
     *
     * @param url 请求 URL
     * @return 响应内容
     */
    public static String sendGet(String url) throws IOException {
        return sendGet(url, null, null);
    }

    public static String sendGet(String url, Map<String, String> params) throws IOException {
        return sendGet(url, null, params);
    }

    /**
     * 发送带参数的 GET 请求
     *
     * @param url    请求 URL
     * @param params 请求参数
     * @return 响应内容
     */
    public static String sendGet(String url, Map<String, String> header, Map<String, String> params) throws IOException {
        return send(url, "GET", header, params);
    }

    public static String sendDelete(String url, Map<String, String> header, Map<String, String> params) throws IOException {
        return send(url, "DELETE", header, params);
    }

    public static String send(String url, String method, Map<String, String> header, Map<String, String> params) throws IOException {
        // 构建带参数的 URL
        if (params != null && !params.isEmpty()) {
            StringBuilder query = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (!query.isEmpty()) {
                    query.append("&");
                }
                query.append(entry.getKey())
                        .append("=")
                        .append(URLEncoder.encode(entry.getValue(), "UTF-8"));
            }
            url += "?" + query.toString();
        }

        HttpURLConnection connection = null;
        try {
            // 创建连接
            URL requestUrl = new URL(url);
            connection = (HttpURLConnection) requestUrl.openConnection();

            // 设置请求方法和超时时间
            connection.setRequestMethod(method);
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            // 添加通用请求头
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0");
            if (header != null) {
                for (Map.Entry<String, String> entry : header.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }

            // 发送请求并获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()))) {
                    return reader.lines()
                            .collect(Collectors.joining(System.lineSeparator()));
                }
            } else {
                throw new IOException("HTTP 请求失败，状态码: " + responseCode);
            }
        } finally {
            // 关闭连接
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    /**
     * 发送 POST 请求（表单形式）
     *
     * @param url    请求 URL
     * @param params 请求参数
     * @return 响应内容
     */
    public static String sendPost(String url, Map<String, String> header, Map<String, String> params) throws IOException {
        HttpURLConnection connection = null;
        try {
            // 创建连接
            URL requestUrl = new URL(url);
            connection = (HttpURLConnection) requestUrl.openConnection();

            // 设置请求方法和超时时间
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            // 添加请求头
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0");
            if (header != null) {
                for (Map.Entry<String, String> entry : header.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }

            // 启用输出流
            connection.setDoOutput(true);

            // 构建表单数据
            StringBuilder formData = new StringBuilder();
            if (params != null && !params.isEmpty()) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    if (formData.length() > 0) {
                        formData.append("&");
                    }
                    formData.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8))
                            .append("=")
                            .append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8));
                }
            }

            // 写入表单数据
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = formData.toString().getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()))) {
                    return reader.lines()
                            .collect(Collectors.joining(System.lineSeparator()));
                }
            } else {
                throw new IOException("HTTP 请求失败，状态码: " + responseCode);
            }
        } finally {
            // 关闭连接
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    /**
     * 发送 POST 请求（JSON 形式）
     *
     * @param url  请求 URL
     * @param json 请求 JSON 数据
     * @return 响应内容
     */
    public static String sendPostJson(String url, Map<String, String> header, String json) throws IOException {
        HttpURLConnection connection = null;
        try {
            // 创建连接
            URL requestUrl = new URL(url);
            connection = (HttpURLConnection) requestUrl.openConnection();

            // 设置请求方法和超时时间
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            // 添加请求头
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0");
            if (header != null) {
                for (Map.Entry<String, String> entry : header.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }

            // 启用输出流
            connection.setDoOutput(true);

            // 写入 JSON 数据
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = json.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()))) {
                    return reader.lines()
                            .collect(Collectors.joining(System.lineSeparator()));
                }
            } else {
                throw new IOException("HTTP 请求失败，状态码: " + responseCode);
            }
        } finally {
            // 关闭连接
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    public static void main(String[] args) throws Exception {

//        String url = "http://103.88.99.2:12007";
////        String requestUrl = "/uc/dict/fetch_item_by_condition";
//        Map<String, String> param = new HashMap<>();
////        param.put("dictType", "tiger_species_type");
////        String response = sendGet(url + requestUrl, param);
////        System.out.println("条件检索字典项: " + response);
////
////        String requestUrl = "/uc/dept/fetch_by_condition";
////        param = new HashMap<>(0);
////        param.put("id", "010101");
////        String response = sendGet(url + requestUrl, param);
////        System.out.println("条件检索单个部门: " + response);
////
//        String requestUrl = "/uc/user/fetch_by_id";
//        param = new HashMap<>(0);
//        param.put("id", "663998002229317");
//        String response = sendGet(url + requestUrl, param);
//        System.out.println("根据用户标识获取用户详情: " + response);

//        String url = "http://192.168.4.90:9998";
//        String requestUrl = "/api/device";
//        String response = sendGet(url + requestUrl);
//        Gson gson = new Gson();
//        R<TbyPageResult<TigerVideoCheckpointBean>> result = gson.fromJson(response, new TypeToken<R<TbyPageResult<TigerVideoCheckpointBean>>>() {
//        }.getType());
//
//        System.out.println(result);
//
//
//        String requestUrl2 = "/api/device/get_device_extend_info_by_deviceno";
//        String response2 = sendGet(url + requestUrl2 + "?deviceno=liubo-test");
//        Gson gson2 = new Gson();
//        R<TigerVideoCheckpointBean> result2 = gson2.fromJson(response2, new TypeToken<R<TigerVideoCheckpointBean>>() {
//        }.getType());
//        System.out.println(result2);
//
//
//        String requestUrl3 = "/api/devicetype";
//        String response3 = sendGet(url + requestUrl3);
//        Gson gson3 = new Gson();
//        R<TbyPageResult<TigerVideoCheckpoint>> result3 = gson3.fromJson(response3, new TypeToken<R<TbyPageResult<TigerVideoCheckpointBean>>>() {
//        }.getType());
//        System.out.println(result3);


    }

}
